#!/usr/bin/env python
# -*- coding:utf8 -*-
import scrapy
import json
import ddddocr
import traceback
from scrapy import Request, cmdline


class chengdufeiyiSpider(scrapy.Spider):
    name = "chengdufeiyi"
    start_urls = ["https://api-changzheng.chinaath.com/changzheng-basic-center-api/api/imageVerify/getUniqueIdByBusinessType?imageVerifyBusinessType=2"]
    yzm_url = "https://api-changzheng.chinaath.com/changzheng-basic-center-api/api/imageVerify/getVerifyCode?uniqueId={}"
    score_url = "https://api-changzheng.chinaath.com/changzheng-score-center-api/api/race/score/user/getCertPathByVerificationCode"
    register_url = "https://api-changzheng.chinaath.com/changzheng-website-center-api/api/official/website/getUserRegistrationBaseInfo"
    header = {
        "Host": "api-changzheng.chinaath.com",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0",
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Content-Type": "application/json",
        "Origin": "https://chengdu.shuzixindong.com",
        "Referer": "https://chengdu.shuzixindong.com/"
    }

    def parse(self, response, **kwargs):
        try:
            data = json.loads(response.text).get("data", "")
            kwargs.update({"imageUniqueId": data})
            url = self.yzm_url.format(data)
            yield Request(url=url, callback=self.yzm_parse, dont_filter=True, cb_kwargs=kwargs)
        except Exception:
            self.logger.error(f"请求imageUniqueId时出错：{traceback.format_exc()}")

    def yzm_parse(self, response, **kwargs):
        try:
            self.logger.info("开始打码")
            image_id = kwargs.get("imageUniqueId", "")
            ocr = ddddocr.DdddOcr(beta=True)
            yzm = ocr.classification(response.body)
            if kwargs.get("score_data", ""):
                regist_data = {"cardNumber": "511321198612302823", "domainName": "chengdu.shuzixindong.com",
                               "imageUniqueId": image_id, "imageVerifyCode": yzm,
                               "raceId": 1000223047}
                yield Request(url=self.register_url, callback=self.register_parse, method="POST", headers=self.header,
                              body=json.dumps(regist_data), dont_filter=True, cb_kwargs=kwargs)
            else:
                score_data = {"raceId": 1000223047, "cardNum": "511321198612302823",
                              "imageUniqueId": image_id, "imageVerifyCode": yzm}
                yield Request(url=self.score_url, callback=self.score_parse, method="POST", headers=self.header,
                              body=json.dumps(score_data), dont_filter=True, cb_kwargs=kwargs)
        except Exception:
            self.logger.error(f"打码时出错：{traceback.format_exc()}")

    def score_parse(self, response, **kwargs):
        try:
            msg = json.loads(response.text).get("msg", "")
            if msg == "验证码错误":
                self.logger.info(f"查询成绩信息时验证码错误，重新打码")
                yield Request(url=self.start_urls[0], callback=self.parse, dont_filter=True, cb_kwargs=kwargs)
            else:
                self.logger.info("开始查询成绩信息")
                data = json.loads(response.text).get("data", [])
                if data:
                    score_img = [f"https://img.shuzixindong.com{path}" for path in data]
                else:
                    score_img = "没有成绩"
                kwargs.update({"score_data": score_img})
                yield Request(url=self.start_urls[0], callback=self.parse, dont_filter=True, cb_kwargs=kwargs)
        except Exception:
            self.logger.error(f"请求成绩信息时出错：{traceback.format_exc()}")

    def register_parse(self, response, **kwargs):
        try:
            msg = json.loads(response.text).get("msg", "")
            if msg == "验证码错误":
                self.logger.info(f"查询报名信息时验证码错误，重新打码")
                yield Request(url=self.start_urls[0], callback=self.parse, dont_filter=True, cb_kwargs=kwargs)
            else:
                self.logger.info("开始查询报名信息")
                register_info = {}
                content = json.loads(response.text)
                data_list = content.get("data", {}).get("registrationFromInfo", [])
                for data in data_list:
                    key = data.get("componentName", "")
                    value = data.get("componentValue", "")
                    register_info[key] = value
                result = {"报名信息": register_info, "成绩": kwargs.get("score_data", "")}
                pass

        except Exception:
            self.logger.error(f"请求报名信息时出错：{traceback.format_exc()}")


if __name__ == '__main__':
    cmdline.execute("scrapy crawl chengdufeiyi".split())
